package com.feihong.txgw.ui.activity.user;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.LogUtils;
import com.feihong.txgw.R;
import com.feihong.txgw.utils.ToastUtils;
import com.feihong.txgw.utils.UserLoginInfo;
import com.feihong.txgw.utils.helper.RxHelper;
import com.feihong.txgw.utils.manage.RetrofitManager;

import org.json.JSONException;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;


public class UserEditPhoneDialog extends Dialog implements View.OnClickListener {
    /**
     * 原手机号码
     */
    private String mUserPhoneNum;
    /**
     * 验证码
     */
    private EditText mVertifyCode;
    /**
     * 获取
     */
    private TextView mQueryCodeBtn;
    /**
     * v
     */
    private TextView mVertifyBtn;
    private TimeCount mTimeCount;
    private EditText mVertifyUserPhNum;
    private TextView codeTitle;

    private UserInfoEditeActivity mContext;
    /**
     * 0修改 1验证  手机号码
     */
    private int reg = 1;
    private static String TAG = "通讯顾问";

    protected UserEditPhoneDialog(Context context, String phoneNum) {
        super(context, R.style.LiuLiangChaXunVertifyCardStype);
        mContext = (UserInfoEditeActivity) context;

        mUserPhoneNum = phoneNum;

        initView();
        bindView();
    }

    public void initView() {
        setContentView(R.layout.activity_user_edit_phone);
        mTimeCount = new TimeCount(60000, 1000);
        mVertifyCode = (EditText) findViewById(R.id.llcx_vertify_code_et);
        mQueryCodeBtn = (TextView) findViewById(R.id.llcx_query_vertify_code_tv);
        mVertifyBtn = (TextView) findViewById(R.id.llcx_vertify_code_btn);
        mVertifyUserPhNum = (EditText) findViewById(R.id.llcx_vertify_user_phNum);
        codeTitle = (TextView) findViewById(R.id.code_title);

        mVertifyCode.addTextChangedListener(watcher);
    }

    private void bindView() {

        if (reg == 0) {
            codeTitle.setText("新的手机号");
            mVertifyUserPhNum.setHint("请输入新手机号");

            mVertifyUserPhNum.setText("");

            mVertifyCode.setText("");

            mQueryCodeBtn.setText("免费获取");
            mVertifyBtn.setText("立即更换");
        } else {

            codeTitle.setText("修改手机号");
            mVertifyUserPhNum.setEnabled(false);
            mVertifyUserPhNum.setText(mUserPhoneNum);
        }

        mVertifyBtn.setOnClickListener(this);
        mQueryCodeBtn.setOnClickListener(this);
        // 屏蔽点击空拍dialog消失
        setCanceledOnTouchOutside(true);

    }

    TextWatcher watcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        @Override
        public void afterTextChanged(Editable s) {
            if (s != null && s.toString().length() == 6) {
                try {
                    if (mContext != null) {
                        InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
                        if (imm.isActive()) {
                            imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);
                        }
                    }
                } catch (Exception e) {

                }
            }
        }
    };


    @Override
    public void onClick(View view) {
        String type = "1";
        String phoneNum = "";
        switch (view.getId()) {
            case R.id.llcx_query_vertify_code_tv:
                mTimeCount.start();
                if (reg == 0) {
                    type = "0";
                }
                //发送验证码
                mVertifyUserPhNum = (EditText) findViewById(R.id.llcx_vertify_user_phNum);
                phoneNum = mVertifyUserPhNum.getText().toString();
                queryVertifyCode(phoneNum, type);
                break;

            case R.id.llcx_vertify_code_btn:

                mVertifyUserPhNum = (EditText) findViewById(R.id.llcx_vertify_user_phNum);
                phoneNum = mVertifyUserPhNum.getText().toString();

                String code = mVertifyCode.getText().toString();

                if (TextUtils.isEmpty(phoneNum)) {
                    mContext.showSystemToast("号码不能为空");
                } else if (!TextUtils.isEmpty(code) && code.length() == 6) {
                    if (reg == 0) {
                        type = "0";
                    }
                    vertifyPhoneNum(phoneNum, code, type);
                } else {
                    mContext.showSystemToast("请输入6位验证码");
                }
                break;
            default:
                break;
        }
    }

    /**
     * 验证手机号
     *
     * @param phoneNum
     * @param code     验证码
     * @param type     0修改 1验证
     */
    private void vertifyPhoneNum(final String phoneNum, String code, String type) {
        LogUtils.i(TAG + "验证手机号 0修改 1验证: " + type);

        KeyboardUtils.hideSoftInput(mContext);

        RetrofitManager.getInstance().updateUserTel(phoneNum, code, type)
                .compose(RxHelper.<String>rxSchedulerHelper())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(String s) {
                        org.json.JSONObject jsonObject = null;
                        try {
                            jsonObject = new org.json.JSONObject(s);
                            String code = jsonObject.optString("code");
                            if ("200".equals(code)) {
                                if (reg == 1) {
                                    mContext.showSystemToast("恭喜你,验证通过了~");
                                    mVertifyUserPhNum.setEnabled(true);
                                    mVertifyUserPhNum.setFocusable(true);
                                    mVertifyUserPhNum.setFocusableInTouchMode(true);
                                    mVertifyUserPhNum.requestFocus();
                                    mVertifyUserPhNum.findFocus();
                                    reg = 0;
                                    //通过 -> 修改手机号码
                                    try {
                                        mTimeCount.cancel();
                                        mTimeCount.onFinish();
                                    } catch (Exception e) {
                                        LogUtils.e(TAG + "-----修改手机号码Exception: -------" + e);
                                    }
                                    bindView();
                                } else {
                                    UserLoginInfo.setUserPhone(phoneNum);
                                    mTimeCount.cancel();
                                    mTimeCount.onFinish();
                                    mContext.showDialog(null, "修改手机号成功", new OnDismissListener() {
                                        @Override
                                        public void onDismiss(DialogInterface dialog) {
                                            mContext.finish();
                                        }
                                    });
                                    cancel();
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }

                    @Override
                    public void onError(Throwable e) {
                        ToastUtils.getInstance().showShortToast("获取验证码失败,请稍后重试~");
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    /**
     * 获取验证码
     */
    private void queryVertifyCode(String phoneNum, String type) {
        RetrofitManager.getInstance().sendTelCodeToLogin(phoneNum, type).compose(RxHelper.<String>rxSchedulerHelper())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(String s) {
                        org.json.JSONObject jsonObject = null;
                        try {
                            jsonObject = new org.json.JSONObject(s);
                            String code = jsonObject.optString("code");
                            if ("200".equals(code)) {
                                ToastUtils.getInstance().showShortToast("验证码已发送");
                            } else {
                                ToastUtils.getInstance().showShortToast(jsonObject.get("msg").toString());
                                mTimeCount.cancel();
                                mTimeCount.onFinish();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        ToastUtils.getInstance().showShortToast("获取验证码失败,请稍后重试~");
                        mTimeCount.cancel();
                        mTimeCount.onFinish();
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private class TimeCount extends CountDownTimer {
        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
            // TODO Auto-generated constructor stub
        }

        @Override
        public void onTick(long millisUntilFinished) {
            // TODO Auto-generated method stub
            mQueryCodeBtn.setClickable(false);
            mQueryCodeBtn.setText(millisUntilFinished / 1000 + "秒");
        }

        @Override
        public void onFinish() {
            // TODO Auto-generated method stub
            mQueryCodeBtn.setClickable(true);
            mQueryCodeBtn.setText("再次获取");
        }
    }

    public void showDialog() {
        show();
        WindowManager windowManager = mContext.getWindowManager();
        Display display = windowManager.getDefaultDisplay();
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        //设置宽度
        lp.width = (int) (display.getWidth());
        getWindow().setAttributes(lp);
    }

}
